package infolayer2.graph;

public class Edge {
  String from;
  String property;
  String to;
  Object value;

  public static String jsonEscape(String s) {
    StringBuilder sb = new StringBuilder(s.length());
    for (int i = 0; i < s.length(); i++) {
      char c = s.charAt(i);
      switch(c) {
      case '\n':
        sb.append("\\n");
        break;
      case '\t':
        sb.append("\\t");
        break;
      case '\'':
        sb.append("\\'");
        break;
      case '"':
        sb.append("\\\"");
        break;
      case '\\':
        sb.append("\\\\");
        break;
      default:
        if (c < ' ') {
          String hex = Integer.toHexString(c);
          sb.append("\\u0000".substring(2 + hex.length()));
          sb.append(hex);
        } else {
          sb.append(c);
        }
      }
    }
    return sb.toString();
  }

  public Edge(String from, String property, String reference, Object value) {
    this.from = from.intern();
    this.property = property.intern();
    this.to = reference == null ? null : reference.intern();
    this.value = value;
  }

  public boolean hasValue() {
    return value != null;
  }
  
  public Object getValue() {
    return value;
  }
  
  public String toString() {
    if (value != null) {
      if (value instanceof String) {
        return "\"" + jsonEscape((String) value) + "\"";
      }
      return "" + value;
    }
    return "'" + jsonEscape(to) + "'";
  }

  public String getTo() {
    return to;
  }

}
